package com.lin.chapter32.chapter3.duty;

import com.lin.chapter32.chapter3.Recorder;

import java.util.Random;

public abstract class DnsServer {
	private DnsServer upperServer;

	public final Recorder resolve(String domain){
		Recorder recorder;
		if (isLocal(domain)) {
			recorder = echo(domain);
		}else {
			recorder = upperServer.resolve(domain);
		}
		return recorder;
	}

	public void setUpperServer(DnsServer upperServer) {
		this.upperServer = upperServer;
	}

	protected abstract boolean isLocal(String domain);

	protected Recorder echo(String domain){
		Recorder recorder = new Recorder();
		recorder.setIp(genIpAddress());
		recorder.setDomain(domain);
		return recorder;
	}

	private String genIpAddress(){
		Random random = new Random();
		return random.nextInt(255) + "." + random.nextInt(255) + "." +
				random.nextInt(255) + "." + random.nextInt(255);
	}
}
